<template>
  <a-modal
    v-model:open="visible"
    title="用户登录"
    :footer="null"
    width="400px"
    centered
    @cancel="handleCancel"
  >
    <a-tabs v-model:active-key="activeTab" centered>
      <!-- 登录 -->
      <a-tab-pane key="login" tab="登录">
        <a-form
          :model="loginForm"
          :rules="loginRules"
          @finish="handleLogin"
          layout="vertical"
        >
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="loginForm.username" placeholder="请输入用户名" />
          </a-form-item>
          
          <a-form-item label="密码" name="password">
            <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" html-type="submit" :loading="loginLoading" block>
              登录
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
      
      <!-- 注册 -->
      <a-tab-pane key="register" tab="注册">
        <a-form
          :model="registerForm"
          :rules="registerRules"
          @finish="handleRegister"
          layout="vertical"
        >
          <a-form-item label="用户名" name="username">
            <a-input v-model:value="registerForm.username" placeholder="请输入用户名" />
          </a-form-item>
          
          <a-form-item label="密码" name="password">
            <a-input-password v-model:value="registerForm.password" placeholder="请输入密码" />
          </a-form-item>
          
          <a-form-item label="确认密码" name="confirmPassword">
            <a-input-password v-model:value="registerForm.confirmPassword" placeholder="请再次输入密码" />
          </a-form-item>
          
          <a-form-item>
            <a-button type="primary" html-type="submit" :loading="registerLoading" block>
              注册
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { login, register } from '@/api/user'

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:open', 'loginSuccess'])

const visible = ref(props.open)
const activeTab = ref('login')
const loginLoading = ref(false)
const registerLoading = ref(false)

// 登录表单
const loginForm = reactive({
  username: '',
  password: '',
  role: 1 // 前台用户
})

// 注册表单
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: ''
})

// 登录表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value) => {
        if (value !== registerForm.password) {
          return Promise.reject('两次输入的密码不一致')
        }
        return Promise.resolve()
      },
      trigger: 'blur'
    }
  ]
}

// 处理登录
const handleLogin = async () => {
  try {
    loginLoading.value = true
    const response = await login(loginForm)
    
    if (response.code === 200) {
      // 保存token
      localStorage.setItem('token', response.data)
      message.success('登录成功')
      
      // 通知父组件登录成功
      emit('loginSuccess')
      handleCancel()
    } else {
      message.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
  } finally {
    loginLoading.value = false
  }
}

// 处理注册
const handleRegister = async () => {
  try {
    registerLoading.value = true
    const { confirmPassword, ...data } = registerForm
    await register(data)
    
    message.success('注册成功，请登录')
    activeTab.value = 'login'
    
    // 清空注册表单
    Object.assign(registerForm, {
      username: '',
      password: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('注册失败:', error)
  } finally {
    registerLoading.value = false
  }
}

// 关闭模态框
const handleCancel = () => {
  visible.value = false
  emit('update:open', false)
  
  // 清空表单
  Object.assign(loginForm, {
    username: '',
    password: '',
    role: 1
  })
  Object.assign(registerForm, {
    username: '',
    password: '',
    confirmPassword: ''
  })
}

// 监听props变化
watch(() => props.open, (val) => {
  visible.value = val
})
</script>

<style scoped>
/* 样式 */
</style>
